Forms API in Django

Manish Patel

Aug 29, 2023

FORMS API

Django does following : -

  • Prepare and restructure data
  • Create HTML form
  • Receive and process submitted client form

Bound Form - it’s bound to data for validation and rendering
Unbound Form - no data to validate and still renders blank form

Two ways to create forms

  • Form API
  • ModelForm

The Django Forms API

  • It is a powerful tool for handling form creation, validation, and rendering in Django applications.
  • It provides an abstraction layer to simplify the process of working with HTML forms and user input.

The key concepts of the Django Forms API

  1. Form Class:
    • A form is defined as a Python class that inherits from django.forms.Form or its subclasses.
    • Each form class represents a specific HTML form and contains fields and validation rules.
  2. Form Fields:
    • Form fields define the data that users can input.
    • Django provides various field classes like CharField, IntegerField, EmailField, and more.
    • Fields specify input types, validation rules, and rendering.
  3. Validation:
    • Form validation ensures that user-submitted data is correct and consistent.
    • Validation rules are specified in field attributes such as required, max_length, min_value, and custom validation methods.
  4. Form Rendering:
    • The Forms API handles rendering form fields into HTML input elements.
    • Form fields are rendered using template tags like {{ form.field_name }} and {{ form.field_name.label_tag }}.

Django forms API

  1. Form Submission:
    • When a user submits a form, Django validates the data and provides a cleaned data dictionary.
    • This dictionary contains cleaned and validated values for each form field.
  2. Form Views:
    • In views, form instances are created and passed to templates for rendering.
    • After submission, the view handles form validation, data processing, and rendering success or error messages.
  3. Form Widgets:
    • Widgets define how form fields are rendered in HTML.
    • They determine the HTML input element’s appearance and behavior.
    • Widgets can be customized or overridden for different field types.
  4. Form Validity:
    • After submission, the is_valid() method checks if the form’s data is valid.
    • If the data is valid, the form’s cleaned data dictionary is populated.

Django forms API

  1. CSRF Protection:
    • Django’s Forms API includes built-in CSRF protection, ensuring that forms submitted on your site are generated by your server and not forged by malicious actors.
  2. Model Forms:
    • Model Forms are a specialized type of form that automatically generates form fields based on a Django model.
    • They facilitate creating, updating, and validating model instances through forms.
  3. Formsets:
    • Formsets allow you to work with multiple instances of a form on a single page.
    • They’re useful for handling related sets of forms, such as inlines or repeating form sections.
  4. Custom Validation:
    • You can define custom validation methods at the form level or field level to implement complex validation logic.
    • These methods are called during form validation.

Django Forms API to create and display forms.

1. Create a Django Project:

  • Start by creating a new Django project named “UserRegistration”:
django-admin startproject userregistration

2. Create a Django App:

  • Create a new app named “accounts” within the project:
   cd userregistration
   python manage.py startapp accounts
  • Register app in settings

3. Define a Form:

  • In the accounts app, define a form for user registration in the forms.py file:
# accounts/forms.py
from django import forms

class RegistrationForm(forms.Form):
   username = forms.CharField(max_length=30)
   email = forms.EmailField()
   password = forms.CharField(widget=forms.PasswordInput)
   confirm_password = forms.CharField(widget=forms.PasswordInput)

4. Create a View:

  • In the accounts app, create a view to handle user registration in the views.py file:
# accounts/views.py
from django.shortcuts import render, redirect
from .forms import RegistrationForm

def register(request):
   if request.method == 'POST':
       form = RegistrationForm(request.POST)
       if form.is_valid():
           # Process the form data (registration logic)
           return redirect('registration_success')
   else:
       form = RegistrationForm()
   return render(request, 'accounts/register.html', {'form': form})

def registration_success(request):
    return render(request, 'accounts/registration_success.html')

5. Configure URLs:

  • Create a URL pattern in the urls.py file of the accounts app to map the register view:
# accounts/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('register/', views.register, name='register'),
    path('registration_success/', views.registration_success, name='registration_success'),
    # Add more URL patterns if needed
]

6. Create Templates:

  • Create a templates directory within the accounts app directory. Inside it, create a register.html template:
<!-- accounts/templates/accounts/register.html -->
<!DOCTYPE html>
<html>
<head>
   <title>User Registration</title>
</head>
<body>
   <h1>User Registration</h1>
   <form method="post">
       {% csrf_token %}
       {{ form.as_p }}
       <button type="submit">Register</button>
   </form>
</body>
</html>

Create a Success Page:

  • Create a template named registration_success.html inside the accounts/templates/accounts directory. This will be the page shown after a successful registration:
<!-- accounts/templates/accounts/registration_success.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Registration Successful</title>
</head>
<body>
    <h1>Registration Successful</h1>
    <p>Your registration was successful. Thank you!</p>
</body>
</html>

7. Run the Development Server:

  • Start the development server:
python manage.py runserver
  • Access the user registration form at http://127.0.0.1:8000/accounts/register/.

  • The form handles user input and can be further extended with validation, registration logic, and more.